import { computed, defineComponent, onMounted, PropType, ref } from "vue";
import {
  VisualEditorBlockData,
  VisualEditorConfig
} from "./visualEditor.utils";
export const VisualEditorBlock = defineComponent({
  props: {
    block: {
      type: Object as PropType<VisualEditorBlockData>
    },
    config: {
      type: Object as PropType<VisualEditorConfig>
    }
    // modelValue: {
    //   type: Object as PropType<VisualEditorBlockData>
    // },
  },
  //  emits:{
  //     'updata:modelValue':(val?: VisualEditorBlockData) => true
  //   },
  setup(props) {
    const el = ref({} as HTMLDivElement);

    const blockClass = computed(()=>[
      'visual-editor-block',
      {
        'visual-editor-block-focus':props.block?.focus
      }
    ])
    const blockStyles = computed(() => ({
      left: `${props.block!.left}px`,
      top: `${props.block!.top}px`,
      zIndex:props.block?.zIndex
    }));

    onMounted(() => {
      /** 如果从左侧列表拖拽进画布，则自动调整组件在鼠标位置居中 */
      const block = props.block;
      if (block?.adjustPosition) {
        const { offsetWidth, offsetHeight } = el.value;
        block.left = props.block!.left - offsetWidth / 2;
        block.top = props.block!.top - offsetHeight / 2;
        block.width = offsetWidth;
        block.height = offsetHeight;
        block.adjustPosition = false;
      }
    });

    const render = computed(()=>props.config?.componentMap[props.block!.componentKey].render);
    return () => (
      <div class={blockClass.value} style={blockStyles.value} ref={el}>
        {render.value}
      </div>
    );
  }
});
